import paho.mqtt.client as mqtt

class MQTT:
    client = mqtt.Client()
    subdict = {} # 这个字典用来存储MQTT频道的返回值
    eventdict = {} # 这个字典用来存储MQTT的绑定关系
    def __init__(self, host:str, port:int, keepalive:int): #初始化MQTT链接，链接MQTT服务器
        '初始化一个MQTT服务器链接\n参数：URL、端口、心跳间隔'
        self.client.connect(host, port, keepalive) # 链接MQTT服务器
        self.client.loop_start() # 开始发送心跳包

    def save_message(msg): # 存放消息
        '自动存放最新消息\n参数：源消息'
        MQTT.subdict[msg.topic] = msg.payload.decode('UTF-8')       
    
    def set_message_event(self, topic:str, function = 'save_message'): # 设置各个频道和函数的绑定关系，默认把它存放到subdict
        '设置事件\n参数：频道、触发函数'
        MQTT.eventdict[topic] = function # 保存到保存绑定关系的列表

    def on_connect(client, userdata, flags, rc):
        '连接成功后rc=0'
        pass
    def on_message(client, userdata, msg): # 来消息时自动执行的函数
        '收到消息后的反应'
        try:
            function = MQTT.eventdict[msg.topic] # 匹配相应频道对应的触发器
            eval(function)
        except:
            MQTT.save_message(msg)

 
        
    client.on_connect = on_connect
    client.on_message = on_message # 当消息来时自动执行函数

    def push(self, topic:str, payload, qos:int=0, retain:bool=False): #在MQTT频道推送消息
        '推送到MQTT频道\n参数：频道、返回值、QOS、Retain'
        self.client.publish(topic, payload, qos, retain)

    def subscribe(self, topic:str): # 订阅MQTT频道
        '订阅MQTT频道\n参数：频道'
        self.subdict[topic] = 'false'
        self.client.subscribe(topic)

    def getFromSub(self, topic:str): # 自MQTT频道获取信息
        return self.subdict.get(topic, "false")
